<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.2" />






<meta name="description" content="记录ResponseIO使用的123">
<meta property="og:type" content="article">
<meta property="og:title" content="Response IO">
<meta property="og:url" content="https://my.oschina.net/u/588736/blog/2016/08/29/response_io/index.html">
<meta property="og:site_name" content="晚来风">
<meta property="og:description" content="记录ResponseIO使用的123">
<meta property="og:updated_time" content="2016-11-28T09:56:24.972Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Response IO">
<meta name="twitter:description" content="记录ResponseIO使用的123">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="https://my.oschina.net/u/588736/blog/2016/08/29/response_io/"/>


  <title> Response IO | 晚来风 </title>
</head>

<body itemscope itemtype="//schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="//schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">晚来风</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">林花谢了春红，太匆匆。</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="//schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Response IO
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-29T00:00:00+08:00" content="2016-08-29">
              2016-08-29
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/JavaWeb/" itemprop="url" rel="index">
                    <span itemprop="name">JavaWeb</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>记录ResponseIO使用的123</p>
<a id="more"></a>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">(HttpServletResponse response)</span> <span class="keyword">throws</span> Exception</span>&#123;</div><div class="line">	<span class="comment">// 使用OutputStream字节流进行数据的输出</span></div><div class="line">	response.getOutputStream().write(<span class="string">"Hello World"</span>.getBytes());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这个例子很简单就是将字符串写到response容器中，然后客户机从容器中拿取数据进行显示即可，但是这里我们需要注意的，当我们在使用response.getOutputStream()这样获取一个OutputStream流的时候，我们在使用完之后，并不需要手动的去关闭，系统会自动关闭它，如果我们手动去关闭这个流的话，还会引发一些问题。<a href="http://blog.csdn.net/jiangwei0910410003/article/details/22886847" target="_blank" rel="external">【来源1】</a> <a href="http://bbs.csdn.net/topics/390801472" target="_blank" rel="external">【来源2】</a></p>
<p>对于response.getWriter():<br><a href="http://bbs.csdn.net/topics/390909701" target="_blank" rel="external">from</a><br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doPost</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span></span></div><div class="line">			<span class="keyword">throws</span> ServletException, IOException &#123;</div><div class="line">		<span class="comment">//将请求、响应的编码均设置为UTF-8（防止中文乱码）</span></div><div class="line">		request.setCharacterEncoding(<span class="string">"UTF-8"</span>);</div><div class="line">		response.setCharacterEncoding(<span class="string">"UTF-8"</span>);</div><div class="line">		<span class="comment">//调用核心业务类处理请求</span></div><div class="line">		String respMessage = CoreService.processRequest(request);</div><div class="line"></div><div class="line">		PrintWriter out = response.getWriter();</div><div class="line">		out.print(respMessage);</div><div class="line"></div><div class="line">		<span class="comment">//释放资源</span></div><div class="line">		out.flush();</div><div class="line">		out.close();</div><div class="line">		out = <span class="keyword">null</span>;</div><div class="line">	&#125;</div></pre></td></tr></table></figure></p>
<p>说明:<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">out.flush(); <span class="comment">//是把输出流立即发送到应答中。</span></div><div class="line">out.close(); <span class="comment">//关掉out锁占用的资源，避免资源占用内存过多，导致一些内存溢出，或者服务器慢，最后没有响应最终挂掉。</span></div><div class="line">out =<span class="keyword">null</span>; <span class="comment">//把次对象编程一个弱引用，当GC运行时方便收回。</span></div></pre></td></tr></table></figure></p>
<p>对于”out=null;”明确地赋值在无穷式循环中是应该的，处理地不恰当当导致内存用光。比如下面这种：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">while</span>(var如果不停机一直运行) &#123;</div><div class="line">   MyBigObject c = <span class="keyword">new</span> MyBigObject();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>看起来这个变量是局部变量，但当如果这个对象占用内存较多时这个循环长时间运行会占用很多内存，可能导致 OutOfMemoberyError 。这个变量虽然声明在 while 循环中，但实际上它在当前方法内都一直存在的，只是仅在 while 循环内可见，只是可见性的差别。这个时候明确地赋值为 null 是应该的。</p>
<p><strong>使用response对象的时候需要注意的问题：</strong><br>就是在使用response进行输出数据的时候，使用两种方式：一种是使用字节流，一种是使用字符流；但是这两种流是不能同时操作的，否在会报异常的，这个只是在使用同一个Response对象的时候会出现这样的问题，比如你在使用转发技术的时候，在一个servlet中使用字节流写数据，然后转发到另一个servlet，在这个servlet中使用字符流写数据，那这样就会有问题，但是如果你是使用了重定向的话，就不会有这样的问题了，因为重定向的话，是在两个Response对象中。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag">#java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/29/annotation02/" rel="next" title="java自定义注解">
                <i class="fa fa-chevron-left"></i> java自定义注解
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/30/Spring_anonymous_bean/" rel="prev" title="Spring之使用匿名bean">
                Spring之使用匿名bean <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="//schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="LenhartG" />
          <p class="site-author-name" itemprop="name">LenhartG</p>
          <p class="site-description motion-element" itemprop="description">美国《时代周刊》2006年度风云人物</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">38</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/gxjares" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/2526255830" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <p class="post-toc-empty">此文章未包含目录</p>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div>
<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="http://music.163.com/outchain/player?type=2&id=208889&auto=1&height=66"></iframe>
</div>
<div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">LenhartG</span>
</div>

<!--
<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>
-->

<!--
<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>
-->
        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.2"></script>



  



  




  
  

  

  

  

  


</body>
</html>
